#include "openslsoundtask.h"
#include "OpenSLES/openslaudioimpl.h"
enum ENUM_SOUND
{
    ENUM_SOUND_START,
    ENUM_SOUND_STOP,
};

typedef struct
{
    int     code;
    int     sampels;
    int     channel;
    int     bitsize;
}Sound_Struct;

OpenSLSoundTask::OpenSLSoundTask()
{
    m_oIAudioData  = 0 ;
    m_oSoundDevice = new  OpenSLAudioImpl;
}

OpenSLSoundTask::~OpenSLSoundTask()
{
    if(m_oSoundDevice)
        delete m_oSoundDevice;
}

void OpenSLSoundTask::Init(IAudioData *impl)
{
    m_oIAudioData = impl;
}

void OpenSLSoundTask::close()
{
    std::string str("");
      int nthread  =thr_count();

      for (int i =0 ;i<nthread ;i++)
          putq(str);

      wait();
}

void OpenSLSoundTask::start(int sampels, int channel, int bitsize)
{
    Sound_Struct soundn_Struct;
    soundn_Struct.code = ENUM_SOUND_START;
    soundn_Struct.sampels = sampels;
    soundn_Struct.channel = channel;
    soundn_Struct.bitsize = bitsize;

    std::string str_buf;
    str_buf.append((char*)&soundn_Struct, sizeof(soundn_Struct));
    putq(str_buf);
}

void OpenSLSoundTask::stop()
{
    Sound_Struct soundn_Struct;
    soundn_Struct.code = ENUM_SOUND_STOP;

    std::string str_buf;
    str_buf.append((char*)&soundn_Struct, sizeof(soundn_Struct));
    putq(str_buf);
}

int OpenSLSoundTask::svc()
{
    std::string str ="";
      while(getq(str))
      {
          if(str=="")
              break;

          const char *pContext    = str.data();

          Sound_Struct *pStruct = (Sound_Struct *)pContext;
          switch (pStruct->code)
          {
          case ENUM_SOUND_START:
              if(m_oSoundDevice && m_oIAudioData)
              {
                   m_oSoundDevice->Init(m_oIAudioData);
                   m_oSoundDevice->Start(pStruct->sampels,pStruct->channel,pStruct->bitsize);
              }
              break;
          case ENUM_SOUND_STOP:
              if(m_oSoundDevice)
                  m_oSoundDevice->Stop();
              break;
          }
      }
      return 0;
}

